<script lang="ts">
import { CacheSeason, CacheTheme } from "@/constants/cacheKey";
import { getCache, setCache } from "@/utils/cache";
import { defineComponent, ref } from "vue";
import baseService from "@/service/baseService";

/**
 * 多语言切换
 */
export default defineComponent({
  name: "Lang",
  props: {
    onChange: Function
  },
  setup(props, { slots }) {
    const seasonList = ref([]);
    const defaultSeason = ref(getCache(CacheSeason, {}, {}));
    // 赛季没有值的话，取最后一条
    if (!defaultSeason.value) {
      // 取seasonList最后一条
      // defaultSeason.value = seasonList[seasonList.value.length - 1];
      baseService.get("/sys/dict/data/page?page=1&limit=20&dictTypeId=2000").then((res) => {
        if (res.code === 0) {
          let list = res.data.list;
          if (list.length > 0) {
            defaultSeason.value = list[list.length - 1].dictValue;
            // 设置赛季
            baseService.get("/sys/setSeason", { season: defaultSeason.value });
          }
        }
      });
    } else {
      // 设置赛季
      baseService.get("/sys/setSeason", { season: defaultSeason.value });
    }

    const onClick = (lang: string) => {
      setCache(CacheSeason, lang);
      defaultSeason.value = lang;
      console.log(defaultSeason);
      props.onChange && props.onChange();
      // 设置赛季
      baseService.get("/sys/setSeason", { season: lang }).then((res) => {
        if (res.code === 0) {
          console.log("设置赛季成功");
          // 刷新页面
          window.location.reload();
        }
      });
    };
    return { defaultSeason, onClick, slots, seasonList };
  },
  created() {
    this.getSeasonList();
  },
  methods: {
    async getSeasonList() {
      await baseService.get("/sys/dict/data/page?page=1&limit=20&dictTypeId=2000").then((res) => {
        if (res.code === 0) {
          let list = res.data.list;
          for (let i = 0; i < list.length; i++) {
            this.seasonList.push(list[i].dictValue);
          }
        }
      });
    }
  }
});
</script>

<template>
  <el-dropdown @command="onClick">
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item v-for="x in seasonList" :key="x" :command="x">{{ x }}</el-dropdown-item>
      </el-dropdown-menu>
    </template>
    <template v-if="slots.default">
      <slot></slot>
    </template>
    <span v-else class="el-dropdown-link" style="display: flex">
      {{ defaultSeason }}
      <el-icon class="el-icon--right" style="font-size: 14px"><arrow-down /></el-icon>
    </span>
  </el-dropdown>
</template>
